/**
 * Created on 2018年3月12日 下午9:06:22
 */
package com.hkb.springboot.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hkb.springboot.dao.StudentDao;
import com.hkb.springboot.entity.StudentEntity;
import com.hkb.springboot.service.StudentService;
import com.hkb.springboot.util.CheckUtils;

/**
 * 学生信息实现类 . <br>
 * 
 * @author hkb <br>
 */
@Service
@Transactional(rollbackFor = Throwable.class)
@CacheConfig(cacheNames = "student")
public class StudentServiceImpl implements StudentService {

    /**
     * 学生信息dao
     */
    @Autowired
    private StudentDao studentDao;
    // private final StudentDao studentDao;
    //
    // /**
    // * 另一种注入方式
    // *
    // * @param studentDao
    // */
    // @Autowired
    // public StudentServiceImpl(StudentDao studentDao) {
    // super();
    // this.studentDao = studentDao;
    // }

    @Override
    public int addStudent(StudentEntity student) {
        studentDao.save(student);
        return student.getId();
    }

    @Override
    public int updateStudent(StudentEntity student) {
        Integer id = student.getId();
        String name = student.getName();
        Integer age = student.getAge();
        CheckUtils.notNull(id, "id不能为空");
        CheckUtils.notEmpty(name, "姓名不能为空");
        CheckUtils.notNull(age, "年龄不能为空");
        // TODO 其他的校验
        return studentDao.save(student).getId();
    }

    @Override
    public boolean deleteStudentById(Integer id) {
        studentDao.delete(id);
        return true;
    }

    @Transactional(readOnly = true, propagation = Propagation.SUPPORTS, rollbackFor = Throwable.class)
    @Cacheable(key = "caches[0].name + ':' + #id")
    @Override
    public StudentEntity findStudentById(Integer id) {
        return studentDao.findOne(id);
    }

    @Transactional(readOnly = true, propagation = Propagation.SUPPORTS, rollbackFor = Throwable.class)
    @Override
    public List<StudentEntity> findStudentByAge(Integer age) {
        return studentDao.findStudentByAge(age);
    }

    @Transactional(readOnly = true, propagation = Propagation.SUPPORTS, rollbackFor = Throwable.class)
    @Override
    public List<StudentEntity> getStudentByAge(Integer age) {
        return studentDao.getStudentByAge(age);
    }

    @Transactional(readOnly = true, propagation = Propagation.SUPPORTS, rollbackFor = Throwable.class)
    @Cacheable(key = "caches[0].name")
    @Override
    public List<StudentEntity> findAllStudent() {
        return studentDao.findAll();
    }

}
